var io = require('socket.io')();
var _ = require('underscore');
var userList=[]
io.on('connection',(socket)=>{
	io.emit('userList',userList);
	//用户上线
	socket.on('login',function(user){
		user.id = socket.id;
		userList.push(user);
		io.emit('userList',userList);
		//成功上线
		socket.emit('userInfo',user);
		//通知其它用户上线信息
		socket.broadcast.emit('loginInfo',user.name+"上线了。");
	});
	//用户下线
	socket.on('disconnect',()=>{
		var user=_.findWhere(userList,{id:socket.id})
		userList=_.without(userList,user)
		if(userList.length){
			io.emit('userList',userList)
			socket.broadcast.emit('loginInfo',user.name+'下线了。')
		}
	})
	//群发消息
	socket.on('toAll',function(msgObj){
		/*
			format:{
				from:{
					name:"",
					img:"",
					id:""
				},
				msg:""
			}
		*/
		socket.broadcast.emit('toAll',msgObj);
	});
	//单发消息
	socket.on('toOne',function(msgObj){
		/*
			format:{
				from:{
					name:"",
					img:"",
					id:""
				},
				to:"",  //socketid
				msg:""
			}
		*/
		//var toSocket = _.findWhere(socketList,{id:msgObj.to});
		var toSocket = _.findWhere(io.sockets.sockets,{id:msgObj.to});
		toSocket.emit('toOne', msgObj);
	});
	//群发图片消息
	socket.on('sendImageToALL',(msgObj)=>{
		socket.broadcast.emit('sendImageToALL',msgObj)
	})
})
exports.listen = function(_server){
	io.listen(_server);
};	